package example1;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

// 实现多线程同步下载图片
public class TestThread2 implements Runnable {
    private String url; // 网络图片的地址

    private String name;  // 保存的文件名

    public TestThread2(String url, String name) {
        this.url = url;
        this.name = name;
    }

    // 下载图片线程的执行体
    @Override
    public void run() {
        WebDownloader webDownloader=new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为："+ name );
    }

    public static void main(String[] args){

//        继承Thread类
//        TestThread2 t1=new
//                TestThread2("https://i1.hdslb.com/bfs/archive/55a3c63cf52355f0b35179758fc4df74c8c29b75.jpg@412w_232h_1c.jpg","1.jpg");
//        TestThread2 t2=new
//                TestThread2("https://i0.hdslb.com/bfs/feed-admin/e2566bc67196ba0f6cd633146d81eec476abcee3.jpg@412w_232h_1c","2.jpg");
//        TestThread2 t3=new
//                TestThread2("https://i0.hdslb.com/bfs/feed-admin/c22765645393e853d4139cf23eb79ef5f689690b.jpg@320w_184h_1c_100q.jpg","3.jpg");
//
//        t1.start();
//        t2.start();
//        t3.start();

//      实现Runnable接口
        TestThread2 t1=new
                TestThread2("https://i1.hdslb.com/bfs/archive/55a3c63cf52355f0b35179758fc4df74c8c29b75.jpg@412w_232h_1c.jpg","1.jpg");
        TestThread2 t2=new
                TestThread2("https://i0.hdslb.com/bfs/feed-admin/e2566bc67196ba0f6cd633146d81eec476abcee3.jpg@412w_232h_1c","2.jpg");
        TestThread2 t3=new
                TestThread2("https://i0.hdslb.com/bfs/feed-admin/c22765645393e853d4139cf23eb79ef5f689690b.jpg@320w_184h_1c_100q.jpg","3.jpg");

        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }
}


// 下载器
class WebDownloader {
    // 下载方法
    public void downloader(String url, String name) {
        try {
            // 拷贝链接的内容到文件中
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,下载失败");
        }
    }
}